package com.jf.anmocker.plugin.injector

import java.io.File
import java.io.FilenameFilter

/**
 * @Class: FileFilter
 * @Description:
 * @author:
 * @Date: 2022/9/22
 */
class FileFilter {

    companion object{

        private fun checkFileType(fileName : String?): Boolean {
            if(fileName == null || fileName.isEmpty()){
                return false
            }
            if(fileName.endsWith(FileFilterConst.CLASS_BUILDCONFIG)
                || fileName.endsWith(FileFilterConst.CLASS_R2)
                || fileName.endsWith(FileFilterConst.CLASS_R)){
                return false
            }
            return fileName.endsWith(FileFilterConst.CLASS_SUFFIX)
        }

        fun getClassFileList(strPath: String?): ArrayList<File>? {
            if(strPath == null || strPath.isEmpty()){
                return null
            }
            val fileList: ArrayList<File> = ArrayList()
            val dir = File(strPath)
            dir.listFiles()?.forEach {file ->
                if (file.isDirectory) {
                    val findFiles = getClassFileList(file.absolutePath)
                    if(findFiles != null && findFiles.isNotEmpty()){
                        fileList.addAll(findFiles)
                    }
                } else if(checkFileType(file.absolutePath)) {
                    fileList.add(file)
                }
            }
            return fileList
        }

        fun filterClassName(className: String) : Boolean {
            if(className.contains("ComposableSingletons\$")
                || className.contains("LiveLiterals\$")
                || className.contains("\$lambda")){
                return false
            }
            return true
        }
    }

}

//排除非Class文件，以及R.Class文件
class ClassNameFilter : FilenameFilter{

    override fun accept(dir : File?, name : String?): Boolean {
        if(name == null || name.isEmpty()){
            return false
        }
        if(name.endsWith(FileFilterConst.CLASS_BUILDCONFIG)
            || name.endsWith(FileFilterConst.CLASS_R2)
            || name.endsWith(FileFilterConst.CLASS_R)){
            return false
        }
        return name.endsWith(FileFilterConst.CLASS_SUFFIX)
    }

}

object FileFilterConst{
    const val CLASS_SUFFIX = ".class"
    const val CLASS_BUILDCONFIG = "BuildConfig.class"
    const val CLASS_R = "R.class"
    const val CLASS_R2 = "R2.class"
    const val DIR_R = "R$"
    const val DIR_R2 = "R2$"
}